<template>
  <a-upload v-model:file-list="fileList" :name="props.name" list-type="picture-card" class="avatar-uploader"
    :show-upload-list="false" :accept="acceptTypes" :max-count="1" :before-upload="beforeUpload" @change="handleChange"
    :custom-request="customRequest">
    <img v-if="imageUrl" :src="imageUrl" alt="avatar"  style="width: 80px; height: 80px;"/>
    <div v-else>
      <loading-outlined v-if="loading"></loading-outlined>
      <plus-outlined v-else></plus-outlined>
      <div class="ant-upload-text">上传图片</div>
    </div>
  </a-upload>
</template>
<script setup>
import { ref,watch } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';


const props = defineProps({
  name: {
    type: String,
    default: 'file'
  },
  defaultUrl: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['upload-success', 'upload-error']);
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
const acceptTypes = '.jpg,.jpeg,.png,.webp';
const fileList = ref([]);
const loading = ref(false);
const imageUrl = ref(props.defaultUrl || '');


watch(
  () => props.defaultUrl,
  (newUrl) => {
    imageUrl.value = newUrl;
  }
);



const customRequest = async ({ file, onSuccess, onError }) => {
  try {
    loading.value = true;

    const formData = new FormData();
    formData.append('file', file);
    const res = await axios.post('/api/files/upload/1', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    if (res?.data?.data && res?.data.code === 200) {
      file.url = res?.data?.data;
      onSuccess(res?.data?.data, file);
      emit('upload-success', res?.data?.data);
    }
    else {
      throw new Error('上传失败，未返回文件路径');
    }
  } catch (error) {
    onError(error);
    emit('upload-error', error);
    message.error('上传失败');
  } finally {
    loading.value = false;
  }
};

const handleChange = info => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    if (!imageUrl.value) {  // 确保只在首次上传时更新 imageUrl
      getBase64(info.file.originFileObj, base64Url => {
        imageUrl.value = base64Url;
        loading.value = false;
      });
    }
    message.success('上传图片成功！');
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
};
const beforeUpload = (file) => {
  // 允许的文件类型
  const allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
  const isAllowedType = allowedTypes.includes(file.type);

  if (!isAllowedType) {
    message.error('只能上传 JPG, JPEG, PNG 或 WEBP 格式的图片!');
    return false;
  }

  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    message.error('图片大小不能超过5MB!');
    return false;
  }

  return true;
};

</script>
<style scoped>
.avatar-uploader>.ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
